<?php
namespace app\common\logic;

class RepeatItemLogic
{

	private function M()
	{
		return M('repeat_item');
	}

	public function ls($pid)
	{
		$pid = (int) $pid;
		if(!$pid) error('参数错误');
		$data = $this->M()->where('pid', $pid)->order("px ASC")->select();
		return $data;
	}

	public function get($id)
	{
		$id = (int) $id;
		$row = $this->M()->find($id);
		return $row;
	}

	//批量保存item
	public function save($post)
	{
		$ids = [];
		//保存item
		foreach ($post as $row)
		{
			$id = (int) $row['id'];
			$pid = (int) $row['pid'];
			if($id) {
				$rs = $this->M()->where('id', $id)->update($row);
				$ids[] = $id;
			}else{
				$ids[] = $this->M()->insertGetId($row);
			}
			if($rs === false) error('保存错误');
		}
		//删除item
		if($pid) {
			$rs = $this->M()->where('pid', $pid)->whereNotIn('id', $ids)->delete();
			if($rs === false) error('删除多余item错误');
		}
	}

	public function del($id)
	{
		$id = (int) $id;
		if(!$id) error('参数错误');
		$rs = $this->M()->where('id', $id)->delete();
		if($rs === false) {
			error('删除失败');
		}else{
			return true;
		}
	}
}